<template>
  <page-layout title="员工管理">
    <div class="staff-management">
      <a-row type="flex" justify="center" align="top">
        <a-col :span="4">
          <a-tree :tree-data="departmentData" :expandedKeys="expandedKeys" :selectedKeys="selectedKeys" :replaceFields="{title:'name', key:'id' }" @select="getJd" @expand="onExpand"></a-tree>
        </a-col>
        <a-col :span="18">
          <a-row type="flex" justify="space-between" align="middle" style="margin-bottom:20px;">
            <a-form layout="inline">
              <a-form-item>
                <a-input v-model="searchField" placeholder="请输入姓名/手机号" allow-clear style="width:220px;">
                  <a-icon slot="prefix" type="user" />
                </a-input>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="onSearch">
                  <a-icon type="search" />查询
                </a-button>
              </a-form-item>
            </a-form>
            <a-button @click="addRole" :disabled="selectedRowKeys.length<=0">
              <a-icon type="plus" />批量添加角色
            </a-button>
          </a-row>
          <!-- <a-table
            class="employees-table"
            :columns="columns"
            :data-source="dataSource"
            :row-selection="rowSelection"
            rowKey="id"
            :pagination="{
                current: page,
                pageSize: pageSize,
                total: total,
                showLessItems: true,
                onChange: onPageChange,
        onShowSizeChange: onSizeChange,
            }"
          >
            <div slot="operation" slot-scope="text, record">
              <a class="ant-dropdown-link" @click="onDetail(record)">详情</a>
            </div>
          </a-table>-->
          <ownTable :columns="columns" :dataSource="dataSource" :selectedRowKeys="selectedRowKeys" @selectedKeys="getSelectedRow" :page="memberState.pageNum" :pageSize="memberState.pageSize" :total="total" @pageChange="onPageChange" @sizeChange="onSizeChange">
            <template slot="operation" slot-scope="record">
              <a class="ant-dropdown-link" @click="onDetail(record.userId)">详情</a>
            </template>
          </ownTable>
        </a-col>
      </a-row>
      <!-- 添加角色弹窗 -->
      <a-modal title="添加角色" v-model="isChangePosition" @ok="handleOk" @cancel="handleCancel" :afterClose="onCloseModal">
        <a-form-model ref="changePosition" :model="changePositionForm" :rules="changePositionRules" :label-col="{span:4}" :wrapper-col="{span:18}">
          <a-form-model-item label="已选员工" prop="employees">
            <a-tag v-for="item in changePositionForm.employees" :key="item.id" closable @close="onDelete(item.id)">{{item.realName}}</a-tag>
          </a-form-model-item>
          <a-form-model-item label="选择角色" prop="position">
            <a-select v-model="changePositionForm.position" placeholder="请选择角色" allow-clear>
              <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="备注内容" prop="note">
            <a-textarea v-model="changePositionForm.note" :max-length="300" :auto-size="{ minRows: 5 }" placeholder="输入内容" allow-clear />
            <span style="position: absolute;right: 10px;bottom: -5px;color: #ccc;">{{changePositionForm.note.length}}/300</span>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
  </page-layout>
</template>

<script>
import PageLayout from "@/layouts/PageLayout";
import ownTable from "@/pages/owns/Table";
import {
  queryEmplyee,
  topDepartment,
  subDepartment
} from '@/services/staff';
import { addMemeber, roleNameList } from '@/services/role'
export default {
  name: "staffManagement",
  components: { ownTable, PageLayout },
  data () {
    return {
      departmentData: [
        {
          name: "组织架构",
          id: "0-0",
          children: []
        }
      ],
      loadedKerList: [],
      searchField: "",
      selectedRowKeys: [],
      changePositionForm: {
        employees: [],
        position: undefined,
        note: ""
      },
      changePositionRules: {
        employees: [
          {
            required: true,
            message: "必须选择员工！",
            trigger: ["change", "blur"]
          }
        ],
        position: [
          { required: true, message: "必须选择职务！", trigger: "change" }
        ],
        note: [{ required: true, message: "内容不允许为空！", trigger: "blur" }]
      },
      columns: [
        {
          title: "姓名",
          dataIndex: "realName",
        },
        {
          title: "部门",
          dataIndex: "deptNames",
        },
        {
          title: "角色",
          dataIndex: "roleNames",
        },
        {
          title: "手机",
          dataIndex: "mobile",
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" }
        }
      ],
      dataSource: [],
      isChangePosition: false,
      size: 2,
      memberState: {
        realName: "",
        mobile: "",
        deptId: "",
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      selectedKeys: [],
      roleList: [],
      expandedKeys: ['0-0']
    };
  },
  methods: {
    // 选中节点触发
    getJd (selectedKeys) {
      const id = selectedKeys[0];
      var bool = this.expandedKeys.includes(id);
      if (!bool) {
        subDepartment({ id }).then(res => {
          if (res.data.code == 200) {
            const data = res.data.data;
            this.departmentData[0].children.forEach(val => {
              if (data.childrenList.length) {
                if (val.id == id) {
                  val.children = data.childrenList
                }
              }
            })
            this.expandedKeys.push(id)
          }
        })
      }
      this.memberState.realName = "";
      this.memberState.mobile = "";
      this.memberState.deptId = selectedKeys[0]
      this.getMemberList(this.memberState)
    },
    onExpand (val) {
      this.expandedKeys = val;
    },
    onSearch () {
      this.memberState.deptId = "";
      this.selectedKeys = []
      isNaN(Number(this.searchField)) ? this.memberState.realName = this.searchField : this.memberState.mobile = this.searchField
      this.getMemberList(this.memberState)
    },
    onDetail (id) {
      this.$router.push({
        path: 'personalDetails',
        query: { id: id }
      });
    },
    addRole () {
      this.isChangePosition = true;
      this.getRoleNameList()
    },
    onDelete (id) {
      this.selectedRowKeys = this.selectedRowKeys.filter(val => val != id);
    },
    handleOk () {
      this.$refs.changePosition.validate(valid => {
        if (valid) {
          this.getAdd();
          this.selectedRowKeys = [];
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.isChangePosition = false;
    },
    handleCancel () {
      this.selectedRowKeys = [];
      this.changePositionForm.employees = [];
      this.$refs.changePosition.resetFields();
    },
    getSelectedRow (data) {
      this.selectedRowKeys = data.selectedRowKeys;
      this.changePositionForm.employees = data.selectedRows;
    },
    onCloseModal () {
      this.handleCancel()
    },
    /**
     * @description: 分页
     * @param {*} page
     * @param {*} pageSize
     * @return {*}
     */
    onPageChange (data) {
      this.memberState.pageNum = data.page
      this.memberState.pageSize = data.pageSize
    },
    onSizeChange (data) {
      this.memberState.pageNum = 1
      this.memberState.pageSize = data.size
    },
    /**
     * @description: 获取组织架构一级部门
     * @param {*}
     * @return {*}
     */
    getTopDepartment () {
      topDepartment().then(res => {
        if (res.data.code == 200) {
          this.departmentData[0].children = res.data.data;
        }
      })
    },
    /**
     * @description: 
     * @param {*}
     * @return {*}
     */
    getMemberList (params) {
      queryEmplyee(params).then(res => {
        if (res.data.code == 200) {
          const data = res.data.data;
          this.dataSource = data.content;
          this.total = data.totalElements;
        }
      })
    },
    getRoleNameList () {
      roleNameList().then(res => {
        if (res.data.code == 200) {
          const data = res.data.data;
          this.roleList = data;
        }
      })
    },
    getAdd () {
      let params = {
        roleId: this.changePositionForm.position,
        userIds: this.selectedRowKeys.toString(),
        status: 0
      }
      addMemeber(params).then(res => {
        if (res.data.code == 200) {
          console.log(res.data.data);
        }
      })
    }
  },
  mounted () {
    // 获取组织架构一级部门
    this.getTopDepartment()
    // 获取默认员工列表
    this.getMemberList(this.memberState)
  },
};
</script>

<style scoped lang="less">
.ant-list-item-meta-content {
  display: flex;
}
.ant-list-item-meta-title {
  margin-right: 10px;
}
.staff-management {
  background: #fff;
  padding-top: 20px;
}
.ant-list-item-meta-description {
  font-size: 12px !important;
}
.ant-list-item-action {
  margin: none !important;
}
</style>
